<?php

namespace app\system\controller;

use app\common\model\BuildLogic;
use app\common\model\CategoryModel;
use app\common\model\FieldLogic;
use app\common\model\FieldModel;
use think\Cache;
use think\Request;

class CmsController extends BaseController
{

    private $cid;
    private $mid;
    private $moudleCache;
    private $moudleName;
    private $categoryCache;
    private $categoryModel;
    private $fieldModel;
    private $fieldLogic;
    private $cmsModel;
    private $tableName;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->cid = $this->request->param('cid/d', 0);
        $this->mid = $this->request->param('mid/d', 0);
        $this->moudleCache = Cache::get('moudle');
        $this->categoryModel = new CategoryModel();
        $this->categoryCache = $this->getCategory();
        $this->fieldModel = new FieldModel();
        if ($this->mid > 0) {
            $this->cmsModel = cms_moudle($this->mid);
            $this->moudleName = $this->moudleCache[$this->mid]['moudle_name'];
            $this->tableName = $this->moudleCache[$this->mid]['table_name'];
            $this->fieldLogic = new FieldLogic($this->tableName);
        }else{
            exit('mid miss');
        }
    }

    /**
     * 获取允许操作栏目
     * @param $siteId
     * @param $uid
     * @return array|mixed
     */
    public function getCategory()
    {
        $category = $this->categoryModel->getSubCategory($this->getGroupId(),$this->mid);
        return $category;
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        if($this->request->has('tpl')){
            $tpl=$this->request->param('tpl');
        }else{
            $tpl=$this->moudleCache[$this->mid]['list_tpl'];
        }
        $this->assign('category', $this->categoryCache);
        $this->assign('moudleName', $this->moudleName);
        return $this->fetch($tpl);
    }

    /**
     * 分页列表
     * @return mixed
     */
    public function pagelist(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="sort desc";
        }
        $where['mid'] = $this->mid;
        $title = $this->request->param('title');
        if (!empty($title)) $where['title'] = ['like', '%' . $title . '%'];
        if ($this->cid > 0) {
            $cids = array_keys(\org\util\TreeUtil::channelList($this->categoryCache, $this->cid, "&nbsp;", 'cid', 'pid'));
            $cids[] = $this->cid; //加入当前栏目
            $where['cid'] = ['in', $cids];
        }
        $map = $this->cmsModel->getExtendMap($this->request->request());
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->cmsModel->where($map)->count(); //检索过后的条数
            if($total==0){
                exception('未检索到数据！',40001);
            }
            $list = $this->cmsModel->field(true)->where($map)->order($order)->page($pageNumber,$pageSize)->select();
            $list = $this->opModel->formatList($list);
            $data['total'] = $total;
            $data['rows'] = $list;
            //$data['sql'] = $this->cmsModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $data['total'] = 0;
            $data['rows'] = [];
            return $data;
        }
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try{
                $data = $this->request->param();
                $buildLogic = new BuildLogic();
                $validate = $buildLogic->buildValidate($this->mid);
                $result = $this->validate($data, $validate['add']);
                if (true !== $result) {
                    exception($result,40001);
                }
                $data['uid'] = $this->getUid();
                $this->cmsModel->add($data);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('添加成功！', url('index', ['mid' => $this->mid, 'cid' => $this->cid]));
        }
        $category = $this->categoryModel->getSelectCat($this->mid,$this->cid);
        if($this->request->has('tpl')){
            $tpl=$this->request->param('tpl');
        }else{
            $tpl=$this->moudleCache[$this->mid]['add_tpl'];
        }
        $layoutForm = $this->fieldLogic->getHtml();
        $this->assign('category', $category);
        $this->assign('layoutForm', $layoutForm);
        $this->assign('moudleName', $this->moudleName);
        $outHtml = $this->fetch($tpl);
        return $this->display($outHtml);
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            try{
                $data = $this->request->param();
                $buildLogic = new BuildLogic();
                $validate = $buildLogic->buildValidate($this->mid);
                $result = $this->validate($data, $validate['edit']);
                if (true !== $result) {
                    exception($result,40001);
                }
                $this->cmsModel->edit($data);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('修改成功！', url('index', ['mid' => $this->mid, 'cid' => $this->cid]));
        }
        $aid = $this->request->param('aid');
        $info = $this->cmsModel->read($aid);
        $info = $this->opModel->formatInfo($info);
        $category = $this->categoryModel->getSelectCat($this->mid,$this->cid);
        if($this->request->has('tpl')){
            $tpl=$this->request->param('tpl');
        }else{
            $tpl=$this->moudleCache[$this->mid]['edit_tpl'];
        }
        $layoutForm = $this->fieldLogic->getHtml($info);
        $this->assign('info',$info);
        $this->assign('category', $category);
        $this->assign('layoutForm', $layoutForm);
        $this->assign('moudleName', $this->moudleName);
        $outHtml = $this->fetch($tpl);
        return $this->display($outHtml);
    }

    /**
     * 删除
     */
    public function del()
    {
        try{
            $aid = $this->request->param('aid');
            $this->cmsModel->del($aid);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！');
    }

    /**
     * 排序
     */
    public function upOrder()
    {
        try{
            $sort = $this->request->param('sort/a');
            if (!empty($sort)) {
                foreach ($sort as $k => $v) {
                    $dataList[] = ['aid' => (int)$k, 'sort' => (int)$v];
                }
                $this->cmsModel->saveAll($dataList);
            } else {
                exception('参数错误！',40001);
            }
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('排序成功', url('index'));
    }

    /**
     * 设置模板
     */
    public function setTpl()
    {
        try{
            $tpl = $this->request->param('tpl/a');
            if (!empty($tpl)) {
                foreach ($tpl as $k => $v) {
                    $dataList[] = ['aid' => (int)$k, 'content_tpl' => $v];
                }
                $this->cmsModel->saveAll($dataList);
            } else {
                exception('参数错误！',40001);
            }
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('模板设置成功', url('index'));
    }

}
